<template>
  <div class="cart">
    <!-- 购物车的头部 -->
        <head-common title="购物车" />
    <!-- 购物车商品列表 -->
    <div class="warp">
      <!-- 购物车为空显示的状态 -->
      <van-empty
        class="custom-image"
        image="https://img.yzcdn.cn/vant/custom-empty-image.png"
        description="购物车竟然是空的！"
        v-if="!items.length"
      />
      <div class="items"  v-for="item in items" :key="item.id">
        <div class="item">
          <van-swipe-cell>
            <div class="item-box">
              <van-checkbox v-model="item.selected" @change="itemSelected(item.key,item.selected)" checked-color="#FF734C" />
              <van-card
                @click="enterDetail(item.goodsId)"
                :num="item.number"
                :desc="  item.characteristic ? item.characteristic: '暂无描述'"
                :price="item.price"
                :title="item.name"
                :thumb="item.pic"
              >
                <template #footer>
                  <van-stepper v-model="item.number"
                   @change="setNum(item.key,item.number)"
                    theme="round" button-size="20" disable-input />
                </template>
              </van-card>
            </div>
            <template #right>
              <van-button square @click="delItem(item.key)"  text="删除" type="danger" class="delete-button" />
            </template>
          </van-swipe-cell>
        </div>
      </div>
    </div>
    <!-- 提交订单栏 -->
    <van-submit-bar :price="total*100" button-text="提交订单" @submit="onSubmit">
      <van-checkbox  checked-color="#FF734C" v-model="allChecked">全选</van-checkbox>
    </van-submit-bar>
    <!-- 底部 -->
    <tabbar/>
  </div>
</template>

<script>
import { mapActions, mapState, mapMutations } from 'vuex'
import { setCartNum, delCartItem, cartItemSelected } from '@api'
import { Dialog, Toast } from 'vant'
import HeadCommon from '../../components/HeadCommon.vue'
import Tabbar from '@components/tabbar'
export default {
  components: {
    HeadCommon,
    Tabbar
  },
  data () {
    return {
      checked: true,
      token: localStorage.getItem('token')
    }
  },
  created () {
    // 调用请求购物车数据函数
    this.get_cart()
  },
  methods: {
    // 点击进入详情页
    enterDetail (id) {
      this.$router.push(`/itemDetail/${id}`)
    },
    // 提交订单 进入订单页
    onSubmit () {
      // 点击进入订单页
      this.$router.replace('/confirmOrder')
    },
    // 修改购物车商品的选中状态
    itemSelected (key, selected) {
      cartItemSelected({
        key,
        selected,
        token: this.token
      }).then(res => {
        if (res.data.code === 0) {
          // 修改后从新赋值
          this.init_cart_info({
            items: res.data.data.items,
            total: res.data.data.price
          })
        }
      })
    },
    // 删除购物车的某条商品
    delItem (key) {
      Dialog.confirm({
        title: '确认移除购物车吗？'
      }).then(() => {
        // 确认删除那就删除吧
        delCartItem({
          key,
          token: this.token
        }).then(res => {
          if (res.data.code === 0) {
            // 删除后提示一下从新赋值
            Toast({
              type: 'success',
              message: '移除成功',
              duration: 1000,
              onClose: () => {
                this.init_cart_info({
                  items: res.data.data.items,
                  total: res.data.data.price
                })
              }
            })
          }
          if (res.data.code === 700) {
            Toast({
              type: 'success',
              message: '什么都没啦',
              duration: 1000,
              onClose: () => {
                this.init_cart_info({
                  items: [],
                  total: 0
                })
              }
            })
          }
        })
      })
    },
    // 修改购物车的购买数量
    setNum (key, number) {
      event.stopPropagation() // 阻止事件冒泡
      setCartNum({
        key,
        number,
        token: this.token
      }).then(res => {
        if (res.data.code === 0) {
          // 修改成功后 从新调用vuex里的mutations里的init_cart_info从新给state里的值赋值
          this.init_cart_info({
            items: res.data.data.items,
            total: res.data.data.price
          })
        }
      })
    },
    // 数据存储在vuex中 调用actions 请求购物车数据
    ...mapActions('cart', ['get_cart']),
    ...mapMutations('cart', ['init_cart_info'])
  },
  computed: {
    ...mapState({
      items: state => state.cart.items,
      total: state => state.cart.total
    }),
    itemKeys () {
      // 得到所有购物车的key
      const keys = []
      this.items.forEach((item) => {
        keys.push(item.key)
      })
      return keys
    },
    // 计算属性 全选依赖与商品的选中状态 如果有一个没选中 那就为false 全部选中才为true
    allChecked: {
      get () {
        // ES5 写法
        // var allChecked = this.items.every(function (item) {
        //   return item.selected
        // })
        // return allChecked

        // ES6写法
        return this.items.every(item => item.selected)
      },
      set (val) {
        // 在set中修改依赖 发送请求将所有的商品的选中状态改变
        cartItemSelected({
          key: this.itemKeys.join(), // join是将数组转换为以逗号分开的字符串 然后传给后端接受
          selected: val, // val 是每次点击全选的状态
          token: this.token
        }).then((res) => {
          if (res.data.code === 0) {
            // 修改成功后在成功赋值
            this.init_cart_info({
              items: res.data.data.items,
              total: res.data.data.price
            })
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.warp {
  padding: 44px 0 100px 0;
  .item-box{
    display: flex;
  }
  .delete-button {
    height: 100%;
  }
  .van-card{
    flex: 1;
    margin: 0;
    .van-card__title{
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 10px;
    }
  }
  .van-submit-bar{
    bottom: 50px !important;
  }
  .van-checkbox{
    background-color: #fafafa;
    padding:10px;
    box-sizing: border-box;
  }
  .van-swipe-cell{
    margin-top: 20px;
  }
  /deep/.van-stepper--round .van-stepper__plus{
    background-color: #FF734C;
  }
  /deep/.van-stepper--round .van-stepper__minus{
    color: #ee0a24;
    border: 1px solid #FF734C;
  }
}
.van-submit-bar {
  bottom: 50px;
}
</style>
